package com.sdhs.workflow.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sdhs.common.utils.ConvertUtils;
import com.sdhs.common.utils.MapstructUtils;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.system.service.ISysDeptService;
import com.sdhs.workflow.domain.WfDefinitionConfig;
import com.sdhs.workflow.domain.bo.WfDefinitionConfigBo;
import com.sdhs.workflow.domain.vo.WfDefinitionConfigVo;
import com.sdhs.workflow.mapper.WfDefinitionConfigMapper;
import com.sdhs.workflow.service.IWfDefinitionConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Collection;

/**
 * 流程定义配置Service业务层处理
 *
 * @author may
 * @date 2024-03-18
 */
@RequiredArgsConstructor
@Service
public class WfDefinitionConfigServiceImpl implements IWfDefinitionConfigService {

    private final WfDefinitionConfigMapper baseMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询流程定义配置
     */
    @Override
    public WfDefinitionConfigVo getByDefId(String definitionId) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<WfDefinitionConfig>().eq(WfDefinitionConfig::getDefinitionId, definitionId));
    }

    /**
     * 查询流程定义配置
     *
     * @param tableName 表名
     * @return 结果
     */
    @Override
    public WfDefinitionConfigVo getByTableNameLastVersion(String tableName) {
        LambdaQueryWrapper<WfDefinitionConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WfDefinitionConfig::getTableName, tableName);
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            // 所属公司id
            String companyId = sysDeptService.selectCompanyIdtByUserId(SecurityUtils.getDeptId());
            wrapper.eq(WfDefinitionConfig::getTenantId, companyId);
        }
        wrapper.orderByDesc(WfDefinitionConfig::getVersion);

        List<WfDefinitionConfigVo> wfDefinitionConfigVos = baseMapper.selectVoList(wrapper);
        if (CollUtil.isNotEmpty(wfDefinitionConfigVos)) {
            return wfDefinitionConfigVos.get(0);
        }
        return null;
    }

    /**
     * 查询流程定义配置
     *
     * @param processKey 表名
     * @return 结果
     */
    @Override
    public WfDefinitionConfigVo getByProcessKeyLastVersion(String processKey) {
        List<WfDefinitionConfigVo> wfDefinitionConfigVos = baseMapper.selectVoList(
                new LambdaQueryWrapper<WfDefinitionConfig>().eq(WfDefinitionConfig::getProcessKey, processKey).orderByDesc(WfDefinitionConfig::getVersion));
        if (CollUtil.isNotEmpty(wfDefinitionConfigVos)) {
            return wfDefinitionConfigVos.get(0);
        }
        return null;
    }

    /**
     * 查询流程定义配置
     *
     * @param definitionId 流程定义id
     * @param tableName    表名
     * @return 结果
     */
    @Override
    public WfDefinitionConfigVo getByDefIdAndTableName(String definitionId, String tableName) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<WfDefinitionConfig>()
            .eq(WfDefinitionConfig::getDefinitionId, definitionId)
            .eq(WfDefinitionConfig::getTableName, tableName));
    }

    /**
     * 查询流程定义配置排除当前查询的流程定义
     *
     * @param tableName    表名
     * @param definitionId 流程定义id
     */
    @Override
    public List<WfDefinitionConfigVo> getByTableNameNotDefId(String tableName, String definitionId) {

        LambdaQueryWrapper<WfDefinitionConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WfDefinitionConfig::getTableName, tableName)
                .ne(WfDefinitionConfig::getDefinitionId, definitionId);

        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            // 所属公司id
            String companyId = sysDeptService.selectCompanyIdtByUserId(SecurityUtils.getDeptId());
            lqw.eq(WfDefinitionConfig::getTenantId, companyId);
        }

        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询流程定义配置列表
     */
    @Override
    public List<WfDefinitionConfigVo> queryList(List<String> definitionIds) {
        return baseMapper.selectVoList(new LambdaQueryWrapper<WfDefinitionConfig>().in(WfDefinitionConfig::getDefinitionId, definitionIds));
    }

    /**
     * 新增流程定义配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdate(WfDefinitionConfigBo bo) {
        // 所属公司id
        String companyId = sysDeptService.selectCompanyIdtByUserId(SecurityUtils.getDeptId());

        WfDefinitionConfig add = ConvertUtils.sourceToTarget(bo, WfDefinitionConfig.class);

        LambdaQueryWrapper<WfDefinitionConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WfDefinitionConfig::getTableName, bo.getTableName());
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            lqw.eq(WfDefinitionConfig::getTenantId, companyId);
        }
        baseMapper.delete(lqw);
        add.setTableName(add.getTableName().toLowerCase());
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            add.setTenantId(companyId);
        }

        boolean flag = false;
        if(add.getId() == null){
            flag = baseMapper.insert(add) > 0;
        } else {
            WfDefinitionConfig wfDefinitionConfig = baseMapper.selectById(add.getId());
            if(wfDefinitionConfig != null){
                flag = baseMapper.updateById(add) > 0;
            }else{
                flag = baseMapper.insert(add) > 0;
            }
        }

        return flag;
    }

    /**
     * 批量删除流程定义配置
     */
    @Override
    public Boolean deleteByIds(Collection<Long> ids) {
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Boolean deleteByDefIds(Collection<String> ids) {
        return baseMapper.delete(new LambdaQueryWrapper<WfDefinitionConfig>().in(WfDefinitionConfig::getDefinitionId, ids)) > 0;
    }
}
